//订单列表
'use strict';
import React,{Component} from 'react';
import Header from '../common/header';
import * as URLconstant from '../constant/URLconstant';
import Alipay from '../common/Alipay';//支付
import Util from '../common/util';
import Toast from '../common/ToastUtil'
import XPay from 'react-native-puti-pay'
import {
    Text,
    View,
    Image,
    TouchableOpacity,
    TextInput,
    ListView,
    Alert,
    DeviceEventEmitter,
    StyleSheet,
    Clipboard,
    FlatList
} from 'react-native'
export default class orderList extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            orderRows:[
                {name:'全部',status:''},
                {name:'待付款',status:'pending'},
                {name:'待发货',status:'accepted'},
                {name:'待收货',status:'shipped'},
                {name:'待评价',status:'finished'},
                {name:'退换货',status:'refund'},
            ],
            page:1,
            limit:10,
            isOver:false,
            again:true,
            hasOrder:true,
            orderList:null,
            loaded:false
        };
        this.renderFooter=this.renderFooter.bind(this)
    }


    async componentDidMount()  {
        let params = this.props.route.params
        await this.setState({
            user_id:params.user_id,
            orderStatus:params.orderStatus
        })
        this.getOrderList()
        let that = this
        DeviceEventEmitter.addListener('orderList', function (Event) {
            // LOG("Event==========" + JSON.stringify(Event));
            let extras = Event.extras;
            let alertContent = Event.alertContent;
            if (extras == 9000) {
                that.getOrderAgain()
            }

        });
    }

    getOrderList(){
        let url = URLconstant.ORDERLIDT_URL
        let datakey=[]
        datakey['user_id']=this.state.user_id
        datakey['page']=this.state.page
        datakey['status'] = this.state.orderStatus;
        datakey['limit']=this.state.limit
        Util.get(url,datakey,this.getOrderListSuc.bind(this),(err)=>{

        })
    }

    getOrderListSuc(datas){
        if(datas.status==0){
            let isOver = false
            let again = true
            let hasOrder = true
            let list = datas.data.list
            let page = this.state.page
            let total = datas.data.total
            if(page==1&&list.length==0){
                hasOrder=false
            }
            if(page==total.total||list.length<total.limit){
                isOver=true
                again = false
            }
            let orderList = this.state.orderList;
            if(orderList==null){
                orderList=[]
            }
            Array.prototype.push.apply(orderList, list);
            this.setState({
                orderList:orderList,
                hasOrder:hasOrder,
                isOver:isOver,
                again:again,
                loaded:true
            })
        }else{
            this.setState({
                orderList:[],
                hasOrder:false,
                isOver:true,
                again:false,
                loaded:true
            })
        }
    }

    async selectStatus(status){
        let loaded = this.state.loaded
        if(!loaded){
            Toast.show('请在数据请求完成后再选择')
            return false;
        }
        await this.setState({
            orderStatus:status,
        })
        this.getOrderAgain()
    }

    async getOrderAgain(){
        await this.setState({
            page:1,
            limit:10,
            isOver:false,
            again:true,
            orderList:null,
            loaded:false
        })
        this.getOrderList()
    }


    showOrderRows(){
        return(
            <View style={styles.order_header}>
                {
                    this.state.orderRows.map((item,index)=>{
                        return(
                            <TouchableOpacity
                                onPress={()=>this.selectStatus(item.status)}
                                key={index} style={styles.order_header_item}>
                                <Text style={item.status==this.state.orderStatus?{fontSize:14,color:"#ee1f12"}:{fontSize:12,color:"#696969"}}>{item.name}</Text>
                            </TouchableOpacity>
                        )
                    })
                }
            </View>
        )
    }

    renderFooter(){
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'center'}}>
                <Text style={{fontSize:12,color:"#969696"}}>{this.state.isOver?"没有更多数据了":"正在加载中"}</Text>
            </View>
        )
    }

    backOrderStatus(status){
        let txt = ''
        if(status==11){
            txt = '待付款'
        }else if(status==16){
            txt = '待成团'
        }else if(status==20){
            txt = '待发货'
        }else if(status==30){
            txt = '待收货'
        }else if(status==40){
            txt = '待评价'
        }else if(status>30&&status<38){
            txt = '退换货'
        }else if(status==0){
            txt = '已取消'
        }
        return <Text style={{fontSize:12,color:"#ee1f12"}}>{txt}</Text>
    }

    //付款
    toPay(item){
        let returnName = 'orderList'
        let order_sn = item.order_sn
        let seller_name = '嘉艺画框'
        let order_amount = item.order_amount
        let alipaySign = item.alipaySign
        LOG('alipaySign=='+alipaySign)
        if(alipaySign){
            XPay.setAlipayScheme('alipayJiayi')
            XPay.alipay(alipaySign,(res)=>this.payResult(res))
            // Alipay.alipayWithTradeNO(order_sn, seller_name, order_amount, returnName,alipaySign);
        }else{
            Toast.show('订单不能支付,请联系客服处理')
        }
    }

    payResult(res){
        LOG('支付结果返回===>>>>'+JSON.stringify(res))
        let that = this
        if (res.resultStatus == 9000) {
            that.getOrderAgain()
            Toast.show('支付成功')
        }else{
            Toast.show(res.memo)
        }
    }

    //复制物流单号
    copy(item){
        let invoice_no = item.invoice_no
        Clipboard.setString(invoice_no);
        Toast.show('复制物流单号成功,请自行前往快递100查看')
    }

    //确认收货
    receivingGoodsAlert(item){
        Alert.alert('嘉艺画框',
            '是否确认收到货物', [
            {text: '取消', onPress: ()=>LOG('点击了取消')},
            {text: '确定', onPress: ()=>this.receivingGoods(item)}
        ])
    }

    //确认收货
    receivingGoods(item){
        let url = URLconstant.CONFIRMRECEIPTURL
        let datakey=[]
        datakey['order_id'] = item.order_id;
        datakey['user_id'] = this.state.user_id;
        Util.get(url,datakey,(datas)=>{
            Toast.show(datas.msg)
            if(datas.status==0){
                this.selectStatus('finished')
            }
        },(err)=>{

        })
    }

    showOperaBtn(item){
        let status = item.status
        if(status==11){
            return(
                <View style={styles.opera_btn_view}>
                    <TouchableOpacity onPress={()=>this.toPay(item)} style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>去付款</Text>
                    </TouchableOpacity>
                </View>
            )
        }else if(status==20){
            return(
                <View style={styles.opera_btn_view}>
                    <View style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>提醒发货</Text>
                    </View>
                </View>
            )
        }else if(status==30){
            return(
                <View style={styles.opera_btn_view}>
                    <TouchableOpacity onPress={()=>this.copy(item)} style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>查看物流</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={()=>this.receivingGoodsAlert(item)} style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>确认收货</Text>
                    </TouchableOpacity>
                </View>
            )
        }else if(status==40){
            return(
                <View style={styles.opera_btn_view}>
                    <View style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>申请售后</Text>
                    </View>
                    <View style={styles.opera_btn}>
                        <Text style={{fontSize:12,color:"#969696"}}>去评价</Text>
                    </View>
                </View>
            )
        }
    }


    //前往订单详情
    toOrderInfo(order_id){
        this.props.navigation.push("OrderInfo",{
            user_id:this.state.user_id,
            order_id:order_id
        })
    }

    _renderRow=({item})=>{
        return(
            <View style={styles.order_item}>
                <TouchableOpacity onPress={()=>this.toOrderInfo(item.order_id)}>
                    <View style={styles.order_rows_view}>
                        <Text style={{fontSize:14,color:"#333"}}>订单号:{item.order_sn}</Text>
                        {this.backOrderStatus(item.status)}
                    </View>
                    {this.showOrderGoods(item.order_goods,item)}
                    <View style={{flexDirection:'row',alignItems:'center',justifyContent:'flex-end',paddingVertical:10}}>
                        <Text style={{fontSize:13,color:"#666"}}>共{item.total}箱商品,合计: </Text>
                        <Text style={{fontSize:13,color:"#ee1f12"}}>¥{item.order_amount}</Text>
                        <Text style={{fontSize:13,color:"#666"}}>(含运费: ¥{item.shipping_fee}{item.coupon_fee>0?",优惠券抵扣:"+item.coupon_fee:null})</Text>
                    </View>
                </TouchableOpacity>
                {this.showOperaBtn(item)}
            </View>
        )
    }


    showOrderGoods(goods,order){
        return(
            <View>
                {
                    goods.map((item,index)=>{
                        return(
                            <View key={item.goods_id}>
                                <View style={[styles.order_rows_view,{paddingBottom:10}]}>
                                    <Text style={{fontSize:14,color:"#ee1f12"}}>{item.shop_name||'总'}仓</Text>
                                    {
                                        order.type!=9?
                                            <Text style={{fontSize:12,color:"#ee1f12"}}>现货</Text>:
                                            <Text style={{fontSize:12,color:"#ee1f12"}}>拼团</Text>
                                    }
                                </View>
                                <View key={index} style={styles.goods_item}>
                                    <Image
                                        source={{uri:item.goods_image}}
                                        resizeMode={'cover'}
                                        style={{width:100,height:100}}
                                    />
                                    <View style={{flex:1,paddingLeft:10,justifyContent:'space-between',height:100}}>
                                        <View>
                                            <Text numberOfLines={2} style={{fontSize:14,color:"#000",marginBottom:10}}>{item.goods_name}</Text>
                                            <Text style={{fontSize:12,color:"#969696"}}>{item.specification}</Text>
                                        </View>
                                        <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
                                            <Text style={{fontSize:12,color:"#ee1f12"}}>{item.price}元/米</Text>
                                            <Text style={{fontSize:12,color:"#ee1f12"}}>{item.quantity}{item.is_means==1?'箱':'支'}</Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        )
                    })
                }
            </View>
        )
    }

    async onEndReached(){
        if(this.state.again){
            await this.setState({
                page:this.state.page+1
            })
            this.getOrderList()
        }
    }


    render() {
        return (
            <View style={{flex:1,backgroundColor:'#f2f2f2'}}>
                <Header navigation={this.props.navigation} title={'我的订单'}/>
                {this.showOrderRows()}
                {
                    this.state.loaded==false?
                        <View style={{flex:1}}>
                            {Util.loading()}
                        </View>:
                        <View style={{flex:1}}>
                            {
                                this.state.hasOrder==false?
                                    <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                                        <Text>没有订单</Text>
                                    </View>:
                                    <FlatList
                                        data={this.state.orderList}
                                        renderItem={this._renderRow}
                                        onEndReached={this.onEndReached.bind(this)}
                                        keyExtractor={item => item.order_id+''}
                                        ListFooterComponent={this.renderFooter}
                                    />
                            }
                        </View>
                }
            </View>
        )
    }
}
var styles = StyleSheet.create({
    order_header:{
        flexDirection:'row',
        alignItems:"center",
        justifyContent:"space-between"
    },
    order_header_item:{
        height:40,
        flex:1,
        alignItems:"center",
        justifyContent:"center"
    },
    order_item:{
        backgroundColor:"#fff",
        marginBottom:10,
        paddingHorizontal:10
    },
    order_rows_view:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'space-between',
        paddingTop:8
    },
    goods_item:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'center',
        paddingBottom:10,
        borderBottomWidth:1,
        borderBottomColor:"#f0f0f0"
    },
    opera_btn_view:{
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'flex-end',
        paddingBottom:10
    },
    opera_btn:{
        width:80,
        height:30,
        borderWidth:1,
        borderColor:"#c0c0c0",
        alignItems:'center',
        justifyContent:'center',
        marginLeft:10
    }

})